package com.asap.demo.mysql.orm;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;


public class DbFetcher implements Serializable{
	private static final Logger logger = LoggerFactory.getLogger(DbFetcher.class);

	private static final long serialVersionUID = 7791139542387021462L;

	Map<String,String> config = null;
	
	public DbFetcher(Map<String,String> config) {
		this.config = config;
	}
	
	public boolean updateMyql(String sql, List<List<String>>params) {
		int result = 0;
		JDBCUtils jdbcInstance = JDBCUtils.getInstance(config);
		Connection conn = jdbcInstance.getC3P0Connection();
		QueryRunner query = new QueryRunner();
		try {
			if(logger.isDebugEnabled())
				logger.debug("更新,SQL-- {}",sql);
			Object[][] params1 = new Object[params.size()][1];//assemble batch insert params
			for (int i = 0; i < params.size(); i++) {
				params1[i] = params.get(i).toArray();
			}
			int[] ret = query.batch(conn,sql,params1);
			return ret.length>0;
		} catch (SQLException e) {
			logger.error("更新数据库异常！"+sql,e);
		}catch(Exception e) {
			throw e;
		}finally {
			jdbcInstance.closeConnect(conn);
		}

		return result>0;
	}


	public boolean  queryMysql(String sql) {
		JDBCUtils jdbcInstance = JDBCUtils.getInstance(config);
		Connection conn = jdbcInstance.getC3P0Connection();
		QueryRunner qr = new QueryRunner();
		try {
			Number num =(Number)qr.query(conn, sql ,new ScalarHandler(1));
			logger.debug("查询异常topic数据是否已经入库了,SQL-- {}",sql+" count:"+ num.intValue());
			return num.intValue()>0;
		} catch (SQLException e) {
			logger.error("查询sql异常！",e);
		}finally {
			jdbcInstance.closeConnect(conn);
		}
		return false;
	}

	public void batchInsertMysql(String sql, List<List<String>>params) {
		JDBCUtils jdbcInstance=null;
		Connection conn=null;
		PreparedStatement pstmt = null;
		try{
			jdbcInstance = JDBCUtils.getInstance(config);
			conn = jdbcInstance.getC3P0Connection();
			pstmt = conn.prepareStatement(sql);

			Object[][] params1 = new Object[params.size()][1];//assemble batch insert params
			for (int i = 0; i < params.size(); i++) {
				params1[i] = params.get(i).toArray();
				for (int index = 0; index < params1[i].length; index++) {
					pstmt.setString(index+1, params1[i][index]+"");
				}
				pstmt.addBatch();
			}
			pstmt.executeBatch();
		} catch (SQLException e) {
			logger.error("executeSql exception,SQL -- "+sql,e);
		}  finally {
			try {
				if (pstmt != null)
					pstmt.close();
			} catch (SQLException e) {
				logger.error("",e);
			} finally {
				if(jdbcInstance!=null)
					jdbcInstance.closeConnect(conn);
			}
		}

	}

}